package com.dayuanit.atm.service;

import com.dayuanit.atm.dto.FlowDTO;
import com.dayuanit.atm.entity.Flow;
import com.dayuanit.atm.mapper.FlowMapper;
import com.dayuanit.atm.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class FlowService {

    @Autowired
    private FlowMapper flowMapper;

    @Autowired
    private RedisService redisService;

    public List<FlowDTO> listTop10(int userId) {

        //先到缓存数据库里查询 如果木有 则到mysql里面查询
        final List<FlowDTO> top10Flows = redisService.getTop10Flows(userId);
        if (null != top10Flows && top10Flows.size() > 0) {
            System.out.println("最近10笔流水从缓存里获取");
            return top10Flows;
        }

        final List<Flow> flows = flowMapper.listTop10(userId);
        final List<FlowDTO> dtoList = new ArrayList<>(flows.size());//3

        for (Flow flow : flows) {
            FlowDTO flowDTO = new FlowDTO();
            dtoList.add(flowDTO);

            flowDTO.setDesc(flow.getFlowDesc());
            flowDTO.setAmount(flow.getAmount());
            flowDTO.setCardNum(flow.getCardNum());
            flowDTO.setCreateTime(DateUtils.dateToString(flow.getCreateTime()));
        }

        // 如果缓存数据库里木有 则放到redis一份
        redisService.saveTop10Flow(userId, dtoList);

        return dtoList;
    }
}
